﻿using CAP.Core.IntegrationEvents;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CAP.Core
{
    public class Startup
    {
        private readonly IConfiguration _config;

        // 通过构造函数注入配置
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddSwaggerGen();
            services.AddUseContext();
            services.AddScoped<SubscriberService>();

            services.AddCap(options =>
            {
                // 存储配置
                options.UseEntityFramework<AppDbContext>();

                // RabbitMQ 配置
                options.UseRabbitMQ(rabbitOptions =>
                {
                    _config.GetSection("RabbitMQ").Bind(rabbitOptions);
                });
                //options.DefaultGroupName = "cap-queue"; // 这会作为队列名称的一部分

                options.UseDashboard(); // 启用仪表盘
                options.FailedRetryCount = 5;
                // 当重试次数达到FailedRetryCount（默认为50次）时，重试会停止
                options.FailedRetryInterval = 10; // 设置每次重试间隔为30秒
                                                  //在消息发送或消费过程中，如果发生失败，CAP会立即重试3次，然后在FallbackWindowLookbackSeconds指定的时间后开始轮询重试
                options.FallbackWindowLookbackSeconds = 30; // 设置重试窗口时间为120秒
                options.SucceedMessageExpiredAfter = 180 * 24 * 3600; // 成功消息保留 24 小时
                options.FailedMessageExpiredAfter = 360 * 24 * 3600; // 失败消息保留 7 天
            });
        }

        public void Configure(IApplicationBuilder app)
        {
            // 4. 初始化数据库
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                dbContext.Database.EnsureCreated(); // 自动创建 CAP 表结构
            }
            // 启用Swagger中间件
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core.API");
                c.RoutePrefix = string.Empty;
            });

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
